<template>
  <div class="match-management">
    <h2>赛程管理</h2>
    <div class="action-buttons">
      <el-button type="primary" @click="showAddDialog">添加比赛</el-button>
    </div>
    <el-table :data="matches" style="width: 100%" :default-sort="{ prop: 'id', order: 'ascending' }">
      <el-table-column prop="id" label="比赛ID" width="180" sortable />
      <el-table-column label="比赛日期" sortable>
        <template #default="scope">
          {{ new Date(scope.row.match_date).toLocaleDateString('zh-CN') }}
        </template>
      </el-table-column>
      <el-table-column prop="match_time" label="比赛时间" />
      <el-table-column prop="week_number" label="比赛周数" />
      <el-table-column prop="venue_name" label="比赛场地" />
      <el-table-column prop="home_school_name" label="主场学校" />
      <el-table-column prop="away_school_name" label="客场学校" />
      <el-table-column prop="home_group_code" label="主场分组" />
      <el-table-column prop="away_group_code" label="客场分组" />
      <el-table-column prop="status" label="状态" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="editMatch(scope.row)">编辑</el-button>
          <el-button size="small" type="primary" @click="viewMatch(scope.row.id)">查看</el-button>
          <el-button size="small" type="danger" @click="deleteMatch(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加比赛' : '编辑比赛'"
      width="30%"
    >
      <el-form :model="form" label-width="80px">
        <el-form-item label="比赛日期">
          <el-date-picker
            v-model="form.match_date"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="比赛时间">
          <el-time-picker
            v-model="form.match_time"
            placeholder="选择时间"
            value-format="HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="比赛周数">
          <el-input-number v-model="form.week_number" :min="1" />
        </el-form-item>
        <el-form-item label="比赛场地">
          <el-select v-model="form.venue_id" placeholder="请选择场地">
            <el-option
              v-for="venue in venues"
              :key="venue.id"
              :label="venue.name"
              :value="venue.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="赛程安排">
          <el-select v-model="form.match_schedule_id" placeholder="请选择赛程">
            <el-option
              v-for="schedule in matchSchedules"
              :key="schedule.id"
              :label="schedule.schedule_name"
              :value="schedule.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="主场学校">
          <el-select v-model="form.home_school_id" placeholder="请选择主场学校">
            <el-option
              v-for="school in schools"
              :key="school.id"
              :label="school.name"
              :value="school.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客场学校">
          <el-select v-model="form.away_school_id" placeholder="请选择客场学校">
            <el-option
              v-for="school in schools"
              :key="school.id"
              :label="school.name"
              :value="school.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="主场分组">
          <el-select v-model="form.home_group_id" placeholder="请选择主场分组">
            <el-option
              v-for="group in scheduleGroups"
              :key="group.id"
              :label="group.group_code"
              :value="group.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客场分组">
          <el-select v-model="form.away_group_id" placeholder="请选择客场分组">
            <el-option
              v-for="group in scheduleGroups"
              :key="group.id"
              :label="group.group_code"
              :value="group.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="待开始" value="pending" />
            <el-option label="进行中" value="in_progress" />
            <el-option label="已结束" value="completed" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const matches = ref([])
const venues = ref([])
const schools = ref([])
const matchSchedules = ref([])
const scheduleGroups = ref([])
const dialogVisible = ref(false)
const dialogType = ref('add')
const form = ref({
  id: null,
  match_date: '',
  match_time: '',
  week_number: 1,
  venue_id: '',
  match_schedule_id: '',
  home_school_id: '',
  away_school_id: '',
  home_group_id: '',
  away_group_id: '',
  status: 'pending'
})

// 获取比赛列表
const fetchMatches = async () => {
  try {
    const response = await axios.get('http://localhost:3000/api/matches')
    matches.value = response.data
  } catch (error) {
    ElMessage.error('获取比赛列表失败')
  }
}

// 获取场地列表
const fetchVenues = async () => {
  try {
    const response = await axios.get('http://localhost:3000/api/venues')
    venues.value = response.data
  } catch (error) {
    ElMessage.error('获取场地列表失败')
  }
}

// 获取学校列表
const fetchSchools = async () => {
  try {
    const response = await axios.get('http://localhost:3000/api/schools')
    schools.value = response.data
  } catch (error) {
    ElMessage.error('获取学校列表失败')
  }
}

// 获取赛程安排列表
const fetchMatchSchedules = async () => {
  try {
    const response = await axios.get('http://localhost:3000/api/match-schedules')
    matchSchedules.value = response.data
  } catch (error) {
    ElMessage.error('获取赛程安排列表失败')
  }
}

// 获取比赛分组列表
const fetchScheduleGroups = async () => {
  try {
    const response = await axios.get('http://localhost:3000/api/schedule-groups')
    scheduleGroups.value = response.data
  } catch (error) {
    ElMessage.error('获取比赛分组列表失败')
  }
}

// 显示添加对话框
const showAddDialog = () => {
  dialogType.value = 'add'
  form.value = {
    match_date: '',
    match_time: '',
    week_number: 1,
    venue_id: '',
    match_schedule_id: '',
    home_school_id: '',
    away_school_id: '',
    home_group_id: '',
    away_group_id: '',
    status: 'pending'
  }
  dialogVisible.value = true
}

// 编辑比赛
const editMatch = (match) => {
  dialogType.value = 'edit'
  form.value = { ...match }
  dialogVisible.value = true
}

// 删除比赛
const deleteMatch = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这场比赛吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await axios.delete(`http://localhost:3000/api/matches/${id}`)
    ElMessage.success('删除成功')
    fetchMatches()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    if (dialogType.value === 'add') {
      await axios.post('http://localhost:3000/api/matches', form.value)
      ElMessage.success('添加成功')
    } else {
      await axios.put(`http://localhost:3000/api/matches/${form.value.id}`, form.value)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    fetchMatches()
  } catch (error) {
    ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
  }
}

// 查看比赛详情
const viewMatch = (id) => {
  router.push(`/match/${id}`)
}

onMounted(() => {
  fetchMatches()
  fetchVenues()
  fetchSchools()
  fetchMatchSchedules()
  fetchScheduleGroups()
})
</script>

<style scoped>
.match-management {
  padding: 20px;
}

.action-buttons {
  margin-bottom: 20px;
}
</style>